package com.yanxu.server;

import com.sun.prism.shader.Solid_TextureYV12_AlphaTest_Loader;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Iterator;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author 折戟沉沙铁未销
 * @version V1.0
 * @date 2025-05-29-2025
 * @Description: 服务端
 */
public class ChatServer {

    private ServerSocket serverSocket;
    private Map<String, Writer> connectedClients;

    /* 构造方法，初始化客户端集合 */
    public ChatServer() {
        this.connectedClients = new ConcurrentHashMap<>();
    }

    /* 添加客户端 */
    public void addClient(Socket socket) throws IOException {
        if (socket != null) {
            // 通过连接 socket ，客户端ip、客户端端口
            String inetAddress = socket.getInetAddress().getHostAddress();
            int port = socket.getPort();
            // 获取 writer
            BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
            // 添加到 map 集合中
            connectedClients.put(inetAddress + port, writer);
            System.out.println(inetAddress + port + " has connected server!!!");
        }
    }

    /* 移除客户端 */
    public void removeClient(Socket socket) throws IOException {
        if (socket != null) {
            // 通过连接 socket ，客户端ip、客户端端口
            String inetAddress = socket.getInetAddress().getHostAddress();
            int port = socket.getPort();
            // 移除客户端
            if (connectedClients.containsKey(inetAddress + port)) {
                // 关闭对应的 writer
                connectedClients.get(inetAddress + port).close();
            }
            // 从map中移除
            connectedClients.remove(inetAddress + port);
            System.out.println(inetAddress + port + " has quit!!!");
        }
    }

    /* 转发消息 */
    public void forwardMessage(Socket socket, String msg) throws IOException {
        // 获取 本次消息 对应的 客户端信息
        String inetAddress = socket.getInetAddress().getHostAddress();
        int port = socket.getPort();
        // 将 msg 消息，转发给其他所有客户端
        Iterator<String> iterator = connectedClients.keySet().iterator();
        while (iterator.hasNext()) {
            String clientName = iterator.next();
            if (!clientName.equals(inetAddress + port)) {
                Writer writer = connectedClients.get(clientName);
                writer.write(msg);
                writer.flush();
            }
        }
    }

    /* 释放资源 */
    public void close(Closeable closeable) {
        if (closeable!=null) {
            try {
                closeable.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /* 启动服务 */
    public void start() {
        try {
            // 绑定监听端口
            serverSocket = new ServerSocket(7777);
            System.out.println("Server started, listening on port 7777");

            while (true) {
                // 等待客户端连接
                Socket socket = serverSocket.accept();

                // 每一个客户端连接过来，就创建一个新的线程，用新创建的线程处理该客户端
                new Thread(new ChatHandler(socket,this)).start();

            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            close(serverSocket);
        }
    }

    public static void main(String[] args) throws IOException {
        ChatServer chatServer = new ChatServer();
        chatServer.start();
    }
}